package middleware

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/convee/goblog/internal/pkg/model"
	"github.com/convee/goblog/internal/pkg/mysql"
	"github.com/convee/goblog/internal/pkg/utils"
)

func VisitLog(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ip := r.Header.Get("X-Real-IP")
		if ip == "" {
			ip = strings.Split(r.RemoteAddr, ":")[0]
		}
		ipInfo, _ := utils.Ip2Region(ip)

		var log model.Visitlog
		log.Ip = ipInfo.Ip
		log.City = ipInfo.City
		log.Country = ipInfo.Country
		log.Province = ipInfo.Province
		log.ClickCount = 1
		log.VisitDate = time.Now()
		row, _ := mysql.UpdateOrAddVisitLogCount(log)
		fmt.Println("row is ", row)
		next.ServeHTTP(w, r)
	})
}
